/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Raytracing.Shaders;

import Raytracing.Shaders.TextureProvider;
import processing.core.PImage;
import processing.core.PVector;

/**
 *
 * @author Matt
 */
public class ImageTexture extends TextureProvider{

    PImage image;
    
    private void degamma( float gamma) {
        float r, g, b;

        for (int i = 0; i < image.pixels.length; i++) {
            r = (image.pixels[i] >> 16) & 0xff;
            g = (image.pixels[i] >> 8) & 0xff;
            b = (image.pixels[i]) & 0xff;

            r /= 255f;
            g /= 255f;
            b /= 255f;


            r = (float) Math.pow(r, 2.2f);
            g = (float) Math.pow(g, 2.2f);
            b = (float) Math.pow(b, 2.2f);

            r *= 255;
            g *= 255;
            b *= 255;
            
            if (r > 255) {
                r = 255;
            }
            if (g > 255) {
                g = 255;
            }
            if (b > 255) {
                b = 255;
            }

            image.pixels[i] = (((int) r) << 16 | (int) g << 8 | (int) b);
        }


    }    
    
    public ImageTexture(PImage image){
        this.image = image;
        degamma(1.8f);
    }
    
    
    public void getColor(float tu, float tv, PVector ret) {
            
            tu = tu%1;
            tv = tv%1;
        
            int ix = (int)(image.width * tu);
            int iy = (int)(image.height * tv);

            int tcolor = image.pixels[iy * image.width + ix];

            ret.set((tcolor >> 16) & 0xff,
                    (tcolor >> 8) & 0xff,
                    (tcolor) & 0xff);

            ret.div(255.f);
    }
    
    
    
    
}
